package com.work.order.controller;

import com.baomidou.dynamic.datasource.DynamicDataSourceCreator;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.work.order.model.TenantBase;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.util.Set;

/**
 * @author qinminghui
 * @description TODO
 * @date 21 14:02
 */
@RestController
@RequestMapping("/tenant")
public class TenantController {
    private static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
    @Autowired
    private DataSource dataSource;
    @Autowired
    private DynamicDataSourceCreator dataSourceCreator;

    @PostMapping
    public Set<String> add(@RequestBody TenantBase tenantBase) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;

        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setDriverClassName(DRIVER_CLASS_NAME);
        dataSourceProperty.setUrl(tenantBase.getUrl());
        dataSourceProperty.setUsername(tenantBase.getUsername());
        dataSourceProperty.setPassword(tenantBase.getPassword());

        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        ds.addDataSource(tenantBase.getId() + "", new DataSourceProxy(dataSource));
        return ds.getCurrentDataSources().keySet();
    }

    @DeleteMapping
    public void remove(String name) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(name);
    }
}
